<style lang="less">
    @import '../../../styles/common.less';
</style>

<template>
    <div>
        <Row :gutter="10">
            <Col span="6">
            <Card>
                <p slot="title">
                    <Icon type="ios-toggle"></Icon>
                    数据字典
                </p>
                <Tree ref="dictionarys" :data="dictionarys" @on-select-change="onSelectChange"></Tree>
            </Card>
            </Col>
            <Col span="18">
            <Card>
                <p slot="title">
                    <Icon type="ios-cog"></Icon>
                    数据字典明细
                </p>
                <Row :gutter="10" type="flex" justify="center" align="middle" class="switch-language-row1">
                    <Col span="24" >
                    <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="120">
                        <FormItem label="数据字典类型" prop="type">
                            <Select  v-model="formValidate.type" placeholder="选择数据字典类型" >
                                <i-option  v-for="dictionaryType in dictionaryTypeEnums" :value="dictionaryType.code" :key="dictionaryType.code">{{dictionaryType.name}}</i-option>
                            </Select>
                        </FormItem>
                        <FormItem label="数据字典名称" prop="name">
                            <Input v-model="formValidate.name" placeholder="输入数据字典名称" :disabled="customerDictionaryTypes.indexOf(formValidate.type)>-1"></Input>
                        </FormItem>
                        <FormItem label="数据字典key" prop="dictionaryKey"  v-if="customerDictionaryTypes.indexOf(formValidate.type)<0">
                            <Input v-model="formValidate.dictionaryKey"  @change.native="handleDictionaryKey" placeholder="输入数据字典key" ></Input>
                        </FormItem>
                        <FormItem label="数据字典key" prop="dictionaryKey" v-if="formValidate.type=='Interface'">
                            <Select  v-model="formValidate.dictionaryKey" placeholder="选择数据字典类型" filterable @on-change="handleNameChange">
                                <i-option  v-for="inter in interfaces" :value="inter.id" :key="inter.id">{{inter.name}}</i-option>
                            </Select>
                        </FormItem>
                        <FormItem label="数据字典key" prop="dictionaryKey" v-if="formValidate.type=='Table'">
                            <Select  v-model="formValidate.dictionaryKey" placeholder="选择数据字典类型" filterable @on-change="handleTableNameChange">
                                <i-option  v-for="inter in tables" :value="inter.id" :key="inter.id">{{inter.name}}</i-option>
                            </Select>
                        </FormItem>
                        <FormItem label="数据字典值" prop="dictionaryValue">
                            <Input v-model="formValidate.dictionaryValue" placeholder="输入数据字典值" :disabled="customerDictionaryTypes.indexOf(formValidate.type)>-1"></Input>
                        </FormItem>
                        <FormItem label="显示顺序" prop="priority" v-if="customerDictionaryTypes.indexOf(formValidate.type)<0">
                            <Select v-model="formValidate.priority" placeholder="选择显示顺序" >
                                <i-option  v-for="sort in 10" :value="sort" :key="sort">{{sort}}</i-option>
                            </Select>
                        </FormItem>
                        <FormItem label="父菜单" prop="parentId" >
                            <Cascader :data="records" filterable v-model="formValidate.fullParentIds" trigger="click" change-on-select></Cascader>
                        </FormItem>
                        <FormItem label="描述" prop="description">
                            <Input v-model="formValidate.description" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入数据字典描述"></Input>
                        </FormItem>
                        <FormItem label="状态" prop="status">
                            <i-switch v-model="statusBoolean" size="large">
                                <span slot="NORMAL">有效</span>
                                <span slot="INVALID">失效</span>
                            </i-switch>
                        </FormItem>
                        <FormItem>
                            <Button type="primary" @click="handlePostOrPut('formValidate')">保存</Button>
                            <Button  @click="handleRest()" style="margin-left: 8px">重置</Button>
                        </FormItem>
                    </Form>
                    </Col>
                </Row>
            </Card>
            </Col>
        </Row>
    </div>
</template>

<script type="text/ecmascript-6">
    import api  from '../../../libs/api'
    import filters from '../../../libs/filters'
    export default {
        name: 'dictionary',
        data () {
            return {
                dictionarys:[
                    {
                        title: '数据字典列表',
                        expand: true,
                        children: []
                    }
                ],
                records:[],
                dictionaryTypeEnums:[], //数据字典类型
                interfaces:[], //资源类型为接口的数据类型
                tables:[],  //资源类型为表格的数据
                customerDictionaryTypes:["Interface","Table"],
                statusBoolean:true,
                formValidate: {
                    id:"",
                    type: '',
                    name:"",
                    dictionaryKey: '',
                    dictionaryValue: '',
                    priority:"",
                    parentId:"",
                    status:"NORMAL",
                    description: '',
                    fullParentIds:[],
                },
                ruleValidate: {
                    name: [
                        { required: true, message: '数据字典名称不能为空', trigger: 'blur' }
                    ],
                    dictionaryKey: [
                        { required: true, message: '数据字典Key不能为空', trigger: 'blur' }
                    ],
                    dictionaryValue:[
                        { required: true, message: '数据字典Value不能为空', trigger: 'blur' }
                    ],
                    type:[
                        { required: true, message: '数据字典类型不允许为空', trigger: 'blur' }
                    ],
                    description: [
                        { required: true, message: '请输入数据字典描述', trigger: 'blur' },
                        { type: 'string', min: 2, message: '数据字典描述长度不小于4', trigger: 'blur' }
                    ]
                }
            }
        },
        methods: {
            //中文且不为空翻译
            handleDictionaryKey(event){
                let self=this;
                event.target.value!=""&&!new RegExp(/[^\u4E00-\u9FA5]/).test(event.target.value)&&this.$get(api.formTemplates.translate,{text:event.target.value}).then((response)=>{
                    if(200==response.code){
                        self.formValidate.dictionaryValue=response.obj;
                    }
                });
            },
            //初始化
            handleInit(){
                let self=this;
                self.$get(api.dictionarys.enum,{type:"DictionaryTypeEnum"}).then(response=>{
                    if(200==response.code){
                        self.dictionaryTypeEnums=response.obj;

                    }
                });
            },
            //接口类型选择对应接口事件
            handleNameChange(val){
                let inter=this.interfaces.filter(v=>{
                    return v.id==val;
                });
                this.formValidate.name=inter[0].name;
                this.formValidate.dictionaryValue=val;
            },
            //表格类型选择对应接口事件
            handleTableNameChange(val){
                let inter=this.tables.filter(v=>{
                    return v.id==val;
                });
                this.formValidate.name=inter[0].name;
                this.formValidate.dictionaryValue=val;
            },

            onSelectChange(data){
                data.expand=!data.expand;
                console.log(data[0]);
                if(typeof data[0] != "undefined"||data[0].nodeKey!=0){
                    this.formValidate=JSON.parse(JSON.stringify(data[0]));  //深度拷贝数据
                }
            },
            //重置
            handleRest(){
                this.$refs["formValidate"].resetFields();
                this.formValidate.fullParentIds=[];
                this.formValidate.id="";
            },
            //读取数据
            handleRead(){
                let self=this;
                let data = {};
                this.$get(api.dictionarys.tree, data).then(response => {
                    var records=[];
                    response.obj.forEach(function (dictionary) {
                        //树形tree所需数据格式
                        dictionary.title=dictionary.name;
                        dictionary.expand=false;
                        //级联组件所需数据格式
                        dictionary.value=dictionary.id;
                        dictionary.label=dictionary.name;
                        dictionary.fullParentIds=filters.split(dictionary.fullParentIds,"/",[]);
                        self.handleTree(dictionary);
                        records.push(dictionary);
                    });
                    self.dictionarys.children=records;
                    self.records=records;
//                    self.dictionaryTypeEnums=records.length>0?records[0].dictionaryTypeEnums:[];
                    self.$set(self.dictionarys[0], 'children', this.records);
                });
            },
            handleTree(dictionary){
                var self=this;
                var childrenArray=[];
                dictionary.childrensView.forEach(function (childrens) {
                    var children={};
                    children=childrens;
                    //树形tree所需数据格式
                    children.title=childrens.name;
                    children.expand=false;
                    //级联组件所需数据格式
                    children.value=childrens.id;
                    children.label=childrens.name;
                    children.fullParentIds=filters.split(children.fullParentIds,"/",[]);
                    childrenArray.push(children);
                });
                dictionary.children=childrenArray;
                childrenArray.forEach(function (item) {
                    if(item.childrensView.length>0)
                        self.handleTree(item);
                    else
                        item.children=[];
                })
            },
            handlePostOrPut (name) {
                let self=this;
                self.$refs[name].validate((valid) => {
                    if (valid) {
                        //去除冗余请求数据
                        delete self.formValidate["children"];
                        delete self.formValidate["childrensView"];
                        let formValidate=JSON.parse(JSON.stringify(self.formValidate));
                        formValidate.parentId=self.formValidate.fullParentIds.length>0?self.formValidate.fullParentIds[self.formValidate.fullParentIds.length-1]:"";
                        formValidate.fullParentIds= filters.separatorArray(self.formValidate.fullParentIds,"/");
                        if(typeof self.formValidate.id=="undefined"||self.formValidate.id==""){   //新增
                            self.$post(api.dictionarys.base,formValidate).then(response => {
                                if(200==response.code){
                                    self.handleRest();
                                    self.handleRead();
                                }
                            });
                        }else{  //更新
                            self.$put(api.dictionarys.base+"/"+self.formValidate.id,formValidate).then(response=>{
                                if(200==response.code){
                                    self.handleRest();
                                    self.handleRead();
                                }
                            });
                        }

                    }
                })
            },
            //请求数据接口
            handleInterfaces(){
                let self=this;
                self.interfaces=[];
                self.$get(api.resources.interface).then(response=>{
                    if(200==response.code){
                        self.interfaces=response.obj;
                    }
                });
            },
            //请求表格数据接口
            handleTables(){
                let self=this;
                self.tables=[];
                self.$get(api.resources.table).then(response=>{
                    if(200==response.code){
                        self.tables=response.obj;
                    }
                });
            }
        },
        created(){
            this.handleInit();
            this.handleRead();
        },

        watch:{
            statusBoolean:function(val, oldVal) {
                this.formValidate.status=val?"NORMAL":"INVALID";
            },
            'formValidate.type':function (val,oldVal) {
                if(val=="Interface"){
                    this.interfaces=[];
                    this.interfaces=this.handleInterfaces();
                }
                if(val=="Table"){
                    this.tables=[];
                    this.tables=this.handleTables();
                }
            }
        }
    }
</script>

<style>

</style>
